<template>
    <page-container>
        <div class="flex left-right-wrap">
            <div class="left-wrap">
                <left-tree v-model:checked="queryParams.projectCode" @checked="handleTreeCheck"></left-tree>
            </div>
            <div class="right-wrap">
                <div class="ant-pro-table">
                    <!-- <div class="ant-pro-table-search">
                        <a-form layout="horizontal">
                            <a-row :gutter="16" type="flex" justify="start">
                                <a-col :xs="12" :sm="12" :md="6" :lg="3">
                                    <a-form-item>
                                        <a-input v-model:value="queryParams.desc" placeholder="管家名称" />
                                    </a-form-item>
                                </a-col>
                                <a-col :xs="24" :sm="24" :md="12" :lg="4">
                                    <a-button @click="handleSearch" type="primary">搜索</a-button>
                                    <a-button @click="handleReset" class="ml-5px">重置</a-button>
                                </a-col>
                            </a-row>
                        </a-form>
                    </div> -->
                    <a-card :body-style="{ padding: 0 }" ref="elRef">
                        <div class="ant-pro-table-list-toolbar">
                            <div class="ant-pro-table-list-toolbar-container">
                                <div class="ant-pro-table-list-toolbar-left"></div>
                                <div class="ant-pro-table-list-toolbar-right">
                                    <a-space align="center">
                                        <!-- <a-button type="primary" @click="basicModalVisible = true">
                                            <plus-outlined />
                                            新建
                                        </a-button> -->
                                        <a-button @click="handleExport" class="ml-10px" :loading="exportLoading" v-permission="[`yfwy:project-relation:export`]">
                                            <download-outlined />
                                            导出
                                        </a-button>
                                        <div class="ant-pro-table-list-toolbar-setting-item">
                                            <a-tooltip title="表格斑马纹">
                                                <a-switch checked-children="开" un-checked-children="关" v-model:checked="fetchDataContext.stripe" />
                                            </a-tooltip>
                                        </div>
                                    </a-space>
                                    <div class="ant-pro-table-list-toolbar-divider">
                                        <a-divider type="vertical" />
                                    </div>
                                    <div class="ant-pro-table-list-toolbar-setting-item">
                                        <a-tooltip title="刷新">
                                            <reload-outlined @click="reload" />
                                        </a-tooltip>
                                    </div>
                                    <div class="ant-pro-table-list-toolbar-setting-item">
                                        <a-tooltip title="密度">
                                            <a-dropdown :trigger="['click']" placement="bottomRight">
                                                <column-height-outlined />
                                                <template #overlay>
                                                    <a-menu
                                                        style="width: 80px"
                                                        :selected-keys="[state.tableSize]"
                                                        @click="
                                                            ({ key }) => {
                                                                fetchDataContext.tableSize = String(key);
                                                            }
                                                        "
                                                    >
                                                        <a-menu-item key="default">
                                                            <a href="javascript:;">默认</a>
                                                        </a-menu-item>
                                                        <a-menu-item key="middle">
                                                            <a href="javascript:;">中等</a>
                                                        </a-menu-item>
                                                        <a-menu-item key="small">
                                                            <a href="javascript:;">紧凑</a>
                                                        </a-menu-item>
                                                    </a-menu>
                                                </template>
                                            </a-dropdown>
                                        </a-tooltip>
                                    </div>
                                    <div class="ant-pro-table-list-toolbar-setting-item">
                                        <a-popover placement="bottomRight" arrowPointAtCenter trigger="click" overlayClassName="ant-pro-table-column-setting-overlay">
                                            <template #title>
                                                <div class="ant-pro-table-column-setting-title">
                                                    <a-checkbox v-model:checked="columnState.checkAll" :indeterminate="columnState.indeterminate" @change="handleColumnAllClick">
                                                        列展示 / 排序
                                                    </a-checkbox>
                                                    <a @click="reset">重置</a>
                                                </div>
                                            </template>
                                            <template #content>
                                                <span class="ant-pro-table-column-setting-list">
                                                    <drag-container
                                                        lockAxis="y"
                                                        dragClass="ant-pro-table-drag-ghost"
                                                        dropClass="ant-pro-table-drop-ghost"
                                                        @drop="({ removedIndex, addedIndex }) => move(removedIndex, addedIndex)"
                                                    >
                                                        <template v-for="column in dynamicColumnItems" :key="column.key">
                                                            <draggable>
                                                                <div class="ant-pro-table-column-setting-list-item">
                                                                    <drag-icon />
                                                                    <a-checkbox :checked="column.checked" @change="handleColumnChange($event, column)">
                                                                        {{ column.label }}
                                                                    </a-checkbox>
                                                                </div>
                                                            </draggable>
                                                        </template>
                                                    </drag-container>
                                                </span>
                                            </template>
                                            <a-tooltip title="列设置">
                                                <setting-outlined />
                                            </a-tooltip>
                                        </a-popover>
                                    </div>
                                    <!-- <div class="ant-pro-table-list-toolbar-setting-item">
                                        <a-tooltip :title="screenState ? '退出全屏' : '全屏'">
                                            <fullscreen-outlined v-if="!screenState" @click="setFull" />
                                            <fullscreen-exit-outlined v-else @click="exitFull" />
                                        </a-tooltip>
                                    </div> -->
                                </div>
                            </div>
                        </div>
                        <a-table
                            :row-class-name="stripe"
                            :size="state.tableSize"
                            :loading="state.loading"
                            :columns="dynamicColumns"
                            :data-source="state.dataSource"
                            :pagination="{
                                'show-size-changer': true,
                                current: state.current,
                                pageSize: state.pageSize,
                                total: state.total,
                                showTotal: total => `共 ${total} 条`,
                            }"
                            ref="tableRef"
                            :getPopupContainer="_trigger => tableRef.$el"
                            @change="handleTableChange"
                        >
                            <template #bodyCell="{ column, record }">
                                <!-- <template v-if="column.dataIndex === 'status'">
                                    <a-badge :status="statusMap[text].status" :text="statusMap[text].text" />
                                </template> -->
                                <template v-if="column.dataIndex === 'action'">
                                    <a-button type="primary" ghost size="small" @click="handleEdit(record)" v-permission="[`yfwy:project-relation:update`]">绑定</a-button>
                                </template>
                            </template>
                        </a-table>
                    </a-card>
                </div>
            </div>
        </div>

        <project-relation-modal :model="basicModalRef" :visible="basicModalVisible" @cancel="basicModalVisible = false" @success="reload" />
    </page-container>
</template>

<script lang="ts">
    import { defineComponent, reactive, ref, watch, watchEffect } from 'vue';
    import {
        PlusOutlined,
        ReloadOutlined,
        ColumnHeightOutlined,
        SettingOutlined,
        FullscreenOutlined,
        FullscreenExitOutlined,
        DownOutlined,
        DownloadOutlined,
    } from '@ant-design/icons-vue';
    import { Container as DragContainer, Draggable } from '@/components/draggable';
    import { getProjectRelationPage, exportProjectRelationExcel } from '@/api/user/project-relation';
    import type { Pagination, TableFilters, TableColumn } from '@/typing';
    import { useFetchData } from '@/utils/hooks/useFetchData';
    import { useFullscreen } from '@/utils/hooks/useFullscreen';
    import { useTableDynamicColumns } from '@/utils/hooks/useTableColumn';
    import DragIcon from '@/components/table/drag-icon.vue';
    import ProjectRelationModal from './project-relation-modal.vue';
    import { downloadByData } from '@/utils/download';

    export default defineComponent({
        name: 'TableList',
        setup() {
            const tableRef = ref();

            const statusMap = {
                0: { text: '关闭', status: 'default' },
                1: { text: '运行中', status: 'processing' },
                2: { text: '已上线', status: 'success' },
                3: { text: '异常', status: 'error' },
            };
            const filteredInfoMap = ref();

            const queryParams = reactive<any>({
                expirationTime: [],
            });
            const fetchDataContext = reactive<any>({
                current: 1,
                pageSize: 10,
                tableSize: 'middle', // 'default' | 'middle' | 'small'
                stripe: false,
                executeImmediately: false,
                requestParams: { ...queryParams },
            });
            watch(
                filteredInfoMap,
                () => {
                    queryParams.status = filteredInfoMap.value?.status;
                    fetchDataContext.requestParams = { ...queryParams };
                },
                { immediate: true },
            );
            const mergedColumns = ref<TableColumn[]>([]);
            watchEffect(() => {
                mergedColumns.value = [
                    {
                        title: '项目名称',
                        dataIndex: 'projectName',
                    },
                    {
                        title: '关联项目',
                        dataIndex: 'relationProjectNames',
                        ellipsis: true,
                    },
                    {
                        title: '操作',
                        dataIndex: 'action',
                    },
                ];
            });
            const needRowIndex = ref(true);
            const {
                state: columnState,
                dynamicColumns,
                dynamicColumnItems,
                handleColumnAllClick,
                handleColumnChange,
                reset,
                move,
            } = useTableDynamicColumns(mergedColumns, { needRowIndex });

            const [elRef, screenState, { setFull, exitFull }] = useFullscreen();

            const { stripe, context: state, reload } = useFetchData(getProjectRelationPage, fetchDataContext);

            const basicModalVisible = ref<boolean>(false);
            const basicModalRef = reactive<any>({});

            const handleTreeCheck = checkedKeys => {
                queryParams.projectCode = checkedKeys.join(',');
                fetchDataContext.executeImmediately = true;
                handleSearch();
            };

            const handleTableChange = ({ current, pageSize }: Pagination, filters?: TableFilters) => {
                filteredInfoMap.value = filters;
                fetchDataContext.current = current;
                fetchDataContext.pageSize = pageSize;
            };

            const handleSearch = () => {
                fetchDataContext.current = 1;
                fetchDataContext.requestParams = { ...queryParams };
            };
            const handleReset = () => {
                fetchDataContext.current = 1;
                fetchDataContext.requestParams = { ...queryParams };
            };

            const handleEdit = (data: any) => {
                Object.assign(basicModalRef, data);
                basicModalVisible.value = true;
            };

            const exportLoading = ref<boolean>(false);
            const handleExport = () => {
                exportLoading.value = true;
                exportProjectRelationExcel({
                    ...fetchDataContext.requestParams,
                    size: 10000000,
                })
                    .then(res => {
                        console.log(res);
                        downloadByData(res, '项目关联.xlsx');
                    })
                    .finally(() => {
                        exportLoading.value = false;
                    });
            };
            return {
                reload,
                statusMap,
                state,
                stripe,
                columnState,
                dynamicColumns,
                dynamicColumnItems,

                queryParams,
                handleSearch,
                handleReset,
                // fullscreen
                elRef,
                screenState,
                setFull,
                exitFull,

                handleTableChange,

                handleColumnChange,
                handleColumnAllClick,
                reset,
                move,

                // modal controls
                tableRef,
                fetchDataContext,

                handleTreeCheck,

                basicModalVisible,
                basicModalRef,
                handleEdit,
                handleExport,
                exportLoading,
            };
        },
        components: {
            DragIcon,
            PlusOutlined,
            ReloadOutlined,
            ColumnHeightOutlined,
            SettingOutlined,
            FullscreenOutlined,
            FullscreenExitOutlined,
            DownOutlined,
            DownloadOutlined,
            Draggable,
            DragContainer,
            ProjectRelationModal,
        },
    });
</script>
